package com.fuyun.rpc.provider.impl;

import cn.hutool.core.util.StrUtil;
import com.fuyun.rpc.config.RpcServiceConfig;
import com.fuyun.rpc.constant.RpcConstant;
import com.fuyun.rpc.factory.SingletonFactory;
import com.fuyun.rpc.provider.ServiceProvider;
import com.fuyun.rpc.registry.ServiceRegistry;
import com.fuyun.rpc.registry.impl.ZkServiceRegistry;
import lombok.SneakyThrows;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author fuyun。
 * @Date 2025/8/22 11:58。
 * @Description: TODO。
 **/

public class ZkServerProvider implements ServiceProvider {
    private final Map<String, Object> SERVER_CACHE = new ConcurrentHashMap<>();

    private final ServiceRegistry serviceRegistry;

    public ZkServerProvider() {
        this(SingletonFactory.getInstance(ZkServiceRegistry.class));
    }

    public ZkServerProvider(ServiceRegistry serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }

    @Override
    public void publishService(RpcServiceConfig config) {
        config.rpcServerNames().forEach(
                serverName -> publishService(serverName, config.getService())
        );


    }

    @SneakyThrows
    private void publishService(String serverName, Object service) {
        String host = InetAddress.getLocalHost().getHostAddress();
        int port = RpcConstant.SERVER_PORT;
        InetSocketAddress address = new InetSocketAddress(host, port);

        serviceRegistry.registerService(serverName, address);
        SERVER_CACHE.put(serverName, service);

    }

    @Override
    public Object getService(String serviceName) {
        if (StrUtil.isBlank(serviceName)) {
            throw new IllegalArgumentException("serviceName can't be null or empty");
        }
        if (!SERVER_CACHE.containsKey(serviceName)) {
            throw new IllegalArgumentException("serviceName not exist");
        }
        return SERVER_CACHE.get(serviceName);
    }
}
